package com.project.controller;

import com.alibaba.fastjson.JSON;
import com.project.dao.IRoleDao;
import com.project.dao.IUserDao;
import com.project.dao.IUserRoleDao;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import util.PageUtil;

import javax.persistence.EntityManager;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author lyl
 * description:
 */
@RestController
@RequestMapping
public class MyController {
    @Autowired
    IRoleDao roleDao;

    @Autowired
    IUserDao userDao;

    @Autowired
    IUserRoleDao iUserRoleDao;

    @Autowired
    EntityManager entityManager;


//    @GetMapping("initData")
//    private String initData() {
//        //生成用户
//        for (int i = 0; i < 20; i++) {
//            UserEntity u = new UserEntity();
//            u.setUsername("测试员" + i);
//            u.setPassword(1000 + i + "");
//            u.setAge(20 + i);
//            userDao.save(u);
//        }
//        //生成角色
//        for (int i = 1; i <= 3; i++) {
//            RoleDto roleEntity = new RoleDto();
//            roleEntity.setRoleDescribe("这是权限" + i + ",用于测试" + System.currentTimeMillis());
//            roleEntity.setRoleName("权限" + i);
//            roleDao.save(roleEntity);
//        }
    //初始化权限
//        List<UserEntity> list = (List<UserEntity>) userDao.findAll();
//        List<RoleDto> list2 = (List<RoleDto>) roleDao.findAll();
//        for (int i = 0; i < list.size(); i++) {
//            //计算访问为1-5之间（保证至少一个权限
//            int x = new Random().nextInt(5) + 1;
//            for (int j = 0; j < x; j++) {
//                UserEntity u = list.get(i);
//                RoleDto r = list2.get(j);
//                UserRoleDto ur = new UserRoleDto();
//                ur.setStatue(1);
//                ur.setRoleEntity(r);
//                ur.setUserEntity(u);
//                iUserRoleDao.save(ur);
//            }
//        }
//        return "初始化数据成功";
//    }

    @GetMapping("findByHQLDto/{username}/{roleName}/{pageNo}")
    private String findByHQLDto(@PathVariable String username, @PathVariable String roleName, @PathVariable int pageNo) {
        //起始位置
        pageNo = (pageNo - 1) * 5;
        List list = iUserRoleDao.findUserHQLDto(username, roleName);
        List list2 = new ArrayList();
        //由于@Query无法进行limit的hql编写，只能手动分页
        for (int i = pageNo + 1; i <= pageNo + 5; i++) {
            if ((i - 1) >= list.size()) {
                break;
            }
            list2.add(list.get(i - 1));
        }
        PageUtil pageUtil = new PageUtil(list2, list.size());
        return JSON.toJSONString(pageUtil);
    }

    @GetMapping("findByHQL/{username}/{roleName}/{pageNo}")
    private String findByHQL(@PathVariable String username, @PathVariable String roleName, @PathVariable int pageNo) {
        String hql = "select userEntity.username,userEntity.age,roleEntity.roleName " +
                "from UserRoleEntity where userEntity.username like '%" + username + "%'" +
                " and roleEntity.roleName like '%" + roleName + "%'";
        List list = entityManager.createQuery(hql).setFirstResult((pageNo - 1) * 5).setMaxResults(5).getResultList();
        List list2 = entityManager.createQuery(hql).getResultList();
        PageUtil pageUtil = new PageUtil(list, list2.size());
        return JSON.toJSONString(pageUtil);
    }

    @GetMapping("findBySqlArr/{username}/{roleName}/{pageNo}")
    private String findBySqlArr(@PathVariable String username, @PathVariable String roleName, @PathVariable int pageNo) {
        Session session = (Session) entityManager.getDelegate();
        String sql = "select u.username, u.age,r.roleName from sys_user u left join sys_user_role ur on u.userId = ur.fk_userId left join sys_role r on r.roleId = ur.fk_roleId " +
                "where u.username like concat('%',?1,'%') and r.roleName like concat('%',?2,'%')";
        int pgn = (pageNo - 1) * 5;
        List<Object[]> objList = session.createNativeQuery(sql)
                .setParameter(1, username)
                .setParameter(2, roleName)
                .setFirstResult(pgn)
                .setMaxResults(5).list();
        int size = session.createNativeQuery(sql).setParameter(1, username).setParameter(2, roleName).list().size();
        PageUtil pageUtil = new PageUtil(objList, size);
        return JSON.toJSONString(pageUtil);
    }

    @GetMapping("findBySqlMap/{username}/{roleName}/{pageNo}")
    private String findBySqlMap(@PathVariable String username, @PathVariable String roleName, @PathVariable int pageNo) {
        Session session = (Session) entityManager.getDelegate();
        String sql = "select u.username, u.age,r.roleName from sys_user u left join sys_user_role ur on u.userId = ur.fk_userId left join sys_role r on r.roleId = ur.fk_roleId " +
                "where u.username like concat('%',?1,'%') and r.roleName like concat('%',?2,'%')";
        int pgn = (pageNo - 1) * 5;
        List<Map> objList = session.createNativeQuery(sql)
                .setParameter(1, username)
                .setParameter(2, roleName)
                .setFirstResult(pgn)
                .setMaxResults(5).list();
        int size = session.createNativeQuery(sql).setParameter(1, username).setParameter(2, roleName).list().size();
        PageUtil pageUtil = new PageUtil(objList, size);
        return JSON.toJSONString(pageUtil);
    }
}
